<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="监测点" prop="monitorId">
        <el-select v-model="queryParams.monitorId" placeholder="请选择监测点" clearable style="width: 280px">
          <el-option
            v-for="dict in monitorIds"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择当前状态" clearable style="width: 180px">
          <el-option
            v-for="dict in sensor_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备SN" prop="deviceSn">
        <el-select v-model="queryParams.deviceSn" placeholder="请选择设备SN" clearable style="width: 180px">
          <el-option
            v-for="dict in deviceSns"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据状态" prop="dataStatus">
        <el-select v-model="queryParams.dataStatus" placeholder="请选择数据状态" clearable style="width: 180px">
          <el-option
            v-for="dict in sensor_data_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['device:sensor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:sensor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:sensor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['device:sensor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table scrollbar-always-on v-loading="loading" :data="sensorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="监测点ID" fixed="left" align="center" prop="monitorId" width="200px">
        <template #default="scope">
          <dict-tag :options="monitorIds" :value="scope.row.monitorId"/>
        </template>
      </el-table-column>
      <el-table-column label="传感器编码" fixed="left" align="center" prop="sensorCode" width="140px"/>
      <el-table-column label="传感器品牌" align="center" prop="sensorBrand" width="120px"/>
      <el-table-column label="传感器型号" align="center" prop="sensorModel" width="120px"/>
      <el-table-column label="传感器类型" align="center" prop="sensorType" width="120px"/>
      <el-table-column label="信号类别" align="center" prop="signalType" >
        <template #default="scope">
          <dict-tag :options="signal_type" :value="scope.row.signalType"/>
        </template>
      </el-table-column>
      <el-table-column label="监测类型" align="center" prop="monitorType" width="180">
        <template #default="scope">
          <dict-tag :options="monitor_type" :value="scope.row.monitorType"/>
        </template>
      </el-table-column>
      <el-table-column label="分辨力" align="center" prop="resolution">
        <template #default="scope">
        <span>
        {{ scope.row.resolution && scope.row.resolution != 0 ? scope.row.resolution : '无' }}
        </span>
        </template>
      </el-table-column>
      <el-table-column label="精度" align="center" prop="accuracy">
        <template #default="scope">
          <dict-tag :options="data_precision" :value="scope.row.accuracy"/>
        </template>
      </el-table-column>
      <el-table-column
          label="采样频率"
          align="center"
          prop="samplingFrequency"
          :formatter="(row) => (!row.samplingFrequency || row.samplingFrequency == 0) ? '无' : row.samplingFrequency"
      />

      <el-table-column label="安装日期" align="center" prop="installationDate" width="180">
        <template #default="scope">
    <span>
      {{ scope.row.installationDate ? parseTime(scope.row.installationDate, '{y}-{m}-{d}') : '无' }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="安装位置" align="center" prop="installationLocation" width="180">
        <template #default="scope">
          <dict-tag :options="monitor_area" :value="scope.row.installationLocation"/>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="state">
        <template #default="scope">
          <dict-tag :options="sensor_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="设备SN" align="center" prop="deviceSn" width="150px">
        <template #default="scope">
          <dict-tag :options="deviceSns" :value="scope.row.deviceSn"/>
        </template>
      </el-table-column>
      <el-table-column label="数据状态" align="center" prop="dataStatus">
        <template #default="scope">
          <dict-tag :options="sensor_data_status" :value="scope.row.dataStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:sensor:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:sensor:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改传感器列表对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="sensorRef" :model="form" :rules="rules" label-width="100px">
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="监测点ID" prop="monitorId">
              <el-select v-model="form.monitorId" placeholder="请选择监测点ID">
                <el-option
                    v-for="dict in monitorIds"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="传感器编码" prop="sensorCode">
              <el-input v-model="form.sensorCode" placeholder="请输入传感器编码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="传感器品牌" prop="sensorBrand">
              <el-input v-model="form.sensorBrand" placeholder="请输入传感器品牌" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="传感器型号" prop="sensorModel">
              <el-input v-model="form.sensorModel" placeholder="请输入传感器型号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="传感器类型" prop="sensorType">
              <el-input v-model="form.sensorType" placeholder="请输入传感器类型" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="信号类别" prop="signalType">
              <el-select v-model="form.signalType" placeholder="请选择信号类别">
                <el-option
                    v-for="dict in signal_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="监测类型" prop="monitorType">
              <el-select v-model="form.monitorType" placeholder="请选择监测类型">
                <el-option
                    v-for="dict in monitor_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="分辨力" prop="resolution">
              <el-input v-model="form.resolution" placeholder="请输入分辨力" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="精度" prop="accuracy">
              <el-select v-model="form.accuracy" placeholder="请选择精度">
                <el-option
                    v-for="dict in data_precision"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="采样频率" prop="samplingFrequency">
              <el-input v-model="form.samplingFrequency" placeholder="请输入采样频率" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="安装日期" prop="installationDate">
              <el-date-picker clearable
                              v-model="form.installationDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择安装日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="安装位置" prop="installationLocation">
              <el-select v-model="form.installationLocation" placeholder="请选择安装位置">
                <el-option
                    v-for="dict in monitor_area"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="当前状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择当前状态">
                <el-option
                    v-for="dict in sensor_state"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备SN" prop="deviceSn">
              <el-select v-model="form.deviceSn" placeholder="请选择设备SN">
                <el-option
                    v-for="dict in deviceSns"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="数据状态" prop="dataStatus">
              <el-select v-model="form.dataStatus" placeholder="请选择数据状态">
                <el-option
                    v-for="dict in sensor_data_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="管养单位" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择管养单位">
                <el-option
                    v-for="dict in sys_dept_list"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Sensor">
import { listSensor, getSensor, delSensor, addSensor, updateSensor } from "@/api/slope/device/sensor/sensor.js";
import {listMonitorPoints} from "@/api/slope/monitorPoints/monitorpoints.js";
import {listDeviceSn} from "@/api/slope/device/deviceInfo/deviceInfo.js";

const { proxy } = getCurrentInstance();
const { monitor_type, data_precision, sys_dept_list, sensor_data_status, sensor_state, signal_type, monitor_area } = proxy.useDict('monitor_type', 'data_precision', 'sys_dept_list', 'sensor_data_status', 'sensor_state', 'signal_type', 'monitor_area');

const deviceSns = ref([])
const monitorIds = ref([])
const sensorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    monitorId: null,
    sensorType: null,
    state: null,
    deviceSn: null,
    dataStatus: null,
  },
  rules: {
    monitorId:[
      { required: true, message: "传感器编码不能为空", trigger: "change" }
    ],
    sensorCode: [
      { required: true, message: "传感器编码不能为空", trigger: "blur" }
    ],
    deviceSn: [
      { required: true, message: "设备SN不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询传感器列表列表 */
function getList() {
  loading.value = true;
  listDeviceSn().then(response => {
    deviceSns.value = response.map(sn => ({
      label: sn,
      value: sn
    }))
  })
  listMonitorPoints().then(response => {
    monitorIds.value = Object.entries(response).map(([key, value]) => ({
      label: key,
      value: value
    }))
  })
  listSensor(queryParams.value).then(response => {
    sensorList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    monitorId: null,
    sensorCode: null,
    sensorBrand: null,
    sensorModel: null,
    sensorType: null,
    signalType: null,
    monitorType: null,
    resolution: null,
    accuracy: null,
    samplingFrequency: null,
    installationDate: null,
    installationLocation: null,
    state: null,
    deviceSn: null,
    dataStatus: null,
    updateTime: null,
    deptId: null
  };
  proxy.resetForm("sensorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加传感器列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSensor(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改传感器列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sensorRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSensor(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSensor(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除传感器列表编号为"' + _ids + '"的数据项？').then(function() {
    return delSensor(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/sensor/export', {
    ...queryParams.value
  }, `sensor_${new Date().getTime()}.xlsx`)
}

getList();
</script>
